package ch.rouge66.energymonitor.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
  
public class EntityManager {

	private static SessionFactory sessionFactory = buildSessionFactory();
    private static Session session;
    private static Transaction transaction;
  
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration();
			return configuration.configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static Session openSession() {
    	session = sessionFactory.openSession();
    	return session;
    }
  
    public void closeSession() {
    	session.close();
    }
    
    public Transaction beginTransaction() {
    	if (session == null || session != null && !session.isOpen()) {
    		session = openSession();
    	}
    	transaction = session.beginTransaction();
    	return transaction;
    }
     
    public void commitTransaction() {
    	transaction.commit();
    }
     
    public void rollbackTransaction() {
    	transaction.rollback();
    }
     
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session getSession() {
        return session;
    }
}
